$(document).ready(function(){

    var provinceTag = document.getElementById("province");
    var provinceTag2 = document.getElementById("province2");
    var provinceTag3 = document.getElementById("province3");
    
    for(var i=0; i<provinceList.length; i++){
        var province = provinceList[i];
        var provinceName = ''
        if(province.name  == '北京'||province.name  == '上海'||province.name  == '天津'||province.name  == '重庆'){
            provinceName = province.name + '市'
        }else{
            provinceName = province.name + '省'
        }
        provinceTag.add(new Option(provinceName,i));
        provinceTag2.add(new Option(provinceName,i));
        provinceTag3.add(new Option(provinceName,i));
    }

    var communityTxt = '',sheng = '',shi = '',qu = ''
    $('#searchBtn').on('click',function(){
        communityTxt = $('.search-box').val()
        sheng = $('#province2').find('option:selected').text()=='请选择'?'':$('#province2').find('option:selected').text()
        shi = $('#city2').find('option:selected').text()=='请选择'?'':$('#city2').find('option:selected').text()
        qu = $('#area2').find('option:selected').text()=='请选择'?'':$('#area2').find('option:selected').text()
        getCommunityList(communityPageNo,showNum,communityTxt,sheng,shi,qu);
        communityTxt = ''
        sheng = ''
        shi = ''
        qu = ''
    })

    //获取社区列表
    var communityPageNo = 1,showNum=10;
    var communityList = '';
    function getCommunityList(p,showNum,communityTxt,sheng,shi,qu){
        getAjax(`${global.apiUrl}/admin_get_community`,function(res){
            console.log(res);
            if(res.list.length == 0){
                $("#page").paging({
                    pageNo:0,
                    totalPage: 0, //总页数
                    totalSize: 0,
                    callback: function(num) {
                        getCommunityList(num,showNum,communityTxt,sheng,shi,qu)
                    }
                });
                var html = `
                        <tr>
                            <td colspan="3" align="center">暂无社区</td>
                        </tr>`
                $('#communityList').html(html);
            }else{
                $("#page").paging({
                    pageNo:p,
                    totalPage: Math.ceil(res.count/showNum), //总页数
                    totalSize: res.count,
                    callback: function(num) {
                        getCommunityList(num,showNum,communityTxt,sheng,shi,qu)
                        communityPageNo = num
                    }
                });
                var html = '';
                var BelongsTag = document.getElementById("Belongs");
                communityList = res.list;
                var list = res.list;
                for(var i in list){
                    html += `
                        <tr>
                            <td>${list[i].community}</td>
                            <td>${list[i].sheng},${list[i].shi},${list[i].qu}</td>
                            <td>${getType(list[i].type)}</td>
                            <td>${getType2(list[i].type,list[i].fid)}</td>
                            <td class="control-td themeColor">
                                <span class="orders" data-id="${list[i].id}" data-sheng="${list[i].sheng}" data-shi="${list[i].shi}" style="margin-left: 15px">查看订单</span>
                                ${getUpgrade(list[i].type,list[i].id)}
                            </td>
                        </tr>
                    `
                    BelongsTag.add(new Option(list[i].community,list[i].id));
                }
                $('#communityList').html(html);
            }
        },{
            p:p,
            num:showNum,
            like: communityTxt,
            sheng: sheng,
            shi: shi,
            qu: qu,
            type: 1
        })
    }
    getCommunityList(communityPageNo,showNum,communityTxt,sheng,shi,qu);

    //升级
    function getUpgrade(type,id){
        var span = ''
        if(type == '3'){
            span += `<span class="upgrade" data-target="#upgradeModal" data-toggle="modal" data-id="${id}" style="margin-left: 15px">升级市代</span> `
        }
        return span
    }

    function getType(type){
        var text = ''
        switch (type) {
            case '1':
                text = '市级代理'
                break;
            case '2':
            case '3':
                text = '区级代理'
                break;
        }
        return text
    }

    function getType2(type,fid){
        var text = ''
        switch (type) {
            case '1':
                text = '无'
                break;
            case '2':
                text = fid
                break;
            case '3':
                text = '无'
                break;
        }
        return text
    }

    $('#province').on('change',function(){
        var province = $(this).find('option:selected').text()
        $("#city").empty();
        $('#city').append('<option value="-1">请选择</option>')
        $("#area").empty();
        $('#area').append('<option value="-1">请选择</option>')
        for(var i=0; i<provinceList.length; i++){
            if(provinceList[i].name == province.substring(0, province.length - 1)){
                if(provinceList[i].cityList){
                    for(var j in provinceList[i].cityList){
                        $('#city').append('<option value="'+j+'">'+provinceList[i].cityList[j].name+'</option>')
                    }
                }
            }
        }
    })
    $('#city').on('change',function(){
        var province = $('#province').find('option:selected').text()
        var city = $(this).find('option:selected').text()
        $("#area").empty();
        $('#area').append('<option value="-1">请选择</option>')
        for(var i=0; i<provinceList.length; i++){
            if(provinceList[i].name == province.substring(0, province.length - 1)){
                if(provinceList[i].cityList){   
                    for(var j in provinceList[i].cityList){
                        if(provinceList[i].cityList[j].name == city){
                            if(provinceList[i].cityList[j].areaList){
                                for(var z in provinceList[i].cityList[j].areaList){
                                    $('#area').append('<option value="'+z+'">'+provinceList[i].cityList[j].areaList[z]+'</option>')
                                }
                                
                            }     
                        }
                    }
                }
            }
        }
    })

    $('#province2').on('change',function(){
        var province2 = $(this).find('option:selected').text()
        $("#city2").empty();
        $('#city2').append('<option value="-1">请选择</option>')
        $("#area2").empty();
        $('#area2').append('<option value="-1">请选择</option>')
        for(var i=0; i<provinceList.length; i++){
            if(provinceList[i].name == province2.substring(0, province2.length - 1)){
                if(provinceList[i].cityList){
                    for(var j in provinceList[i].cityList){
                        $('#city2').append('<option value="'+j+'">'+provinceList[i].cityList[j].name+'</option>')
                    }
                }
            }
        }
    })
    $('#city2').on('change',function(){
        var province2 = $('#province2').find('option:selected').text()
        var city2 = $(this).find('option:selected').text()
        $("#area2").empty();
        $('#area2').append('<option value="-1">请选择</option>')
        for(var i=0; i<provinceList.length; i++){
            if(provinceList[i].name == province2.substring(0, province2.length - 1)){
                if(provinceList[i].cityList){   
                    for(var j in provinceList[i].cityList){
                        if(provinceList[i].cityList[j].name == city2){
                            if(provinceList[i].cityList[j].areaList){
                                for(var z in provinceList[i].cityList[j].areaList){
                                    $('#area2').append('<option value="'+z+'">'+provinceList[i].cityList[j].areaList[z]+'</option>')
                                }
                                
                            }     
                        }
                    }
                }
            }
        }
    })

    $('#province3').on('change',function(){
        var province3 = $(this).find('option:selected').text()
        $("#city3").empty();
        $('#city3').append('<option value="-1">请选择</option>')
        $("#area3").empty();
        $('#area3').append('<option value="-1">请选择</option>')
        for(var i=0; i<provinceList.length; i++){
            if(provinceList[i].name == province3.substring(0, province3.length - 1)){
                if(provinceList[i].cityList){
                    for(var j in provinceList[i].cityList){
                        $('#city3').append('<option value="'+j+'">'+provinceList[i].cityList[j].name+'</option>')
                    }
                }
            }
        }
    })

    $('#CommunityModal').on('show.bs.modal',function(event){
        var modal = $(this);
        var account = modal.find('#account');
        account.val('');
        var password = modal.find('#password');
        password.val('');
        var communityPhone = modal.find('#communityPhone');
        communityPhone.val('');
        var communityName = modal.find('#communityName');
        communityName.val('');
        var rebate = modal.find('#rebate');
        rebate.val('');
        var rebate2 = modal.find('#rebate2');
        rebate2.val('');
        $("#province").val("-1");
        $("#city").val("-1");
        $("#area").val("-1");       
        var obj = $(".class-checked");
        obj.attr('checked',false);
        obj.each(function(){
            var that = $(this);
            if(that.val() == '2'){
                that.prop('checked',true);
            }
        })
        $('.rebateAre').hide()
        $('.Belongs').show()
        $('#Belongs').val("-1")
    })

    $('.class-checked').on('click',function(){
        var type = $(this).val()
        if(type == 1){
            $('.rebateAre').show()
            $('.Belongs').hide()
        }else if(type == 2){
            $('.rebateAre').hide()
            $('.Belongs').show()
        }
    })

    /** 添加 社区 **/
    $('#addCommunity').on('click',function(){
        var account = $('#account').val();
        var password = $('#password').val();
        var rebate = Number($('#rebate').val()/100);
        var rebate2 = Number($('#rebate2').val()/100);
        var communityName = $('#communityName').val();
        var communityPhone = $('#communityPhone').val();
        var province = $('#province').find('option:selected').text()
        var city = $('#city').find('option:selected').text()
        var area = $('#area').find('option:selected').text()
        var obj = document.getElementsByClassName("class-checked");
        var belongs = $('#Belongs').find('option:selected').text();//所属市代
        var check_class = '';
        var fid = 0
        var type
        for(k in obj){
            if(obj[k].checked)
                check_class=obj[k].value;
        }
        if(check_class == 2){
            rebate = 0
            if(belongs != '请选择'){
                fid = $('#Belongs').val()
                type = 2
            }else{
                type = 3
            }
        }else if(check_class == 1){
            if(rebate == ''|| rebate == 0){
                alert('请填写市级代理返利！')
            }
            type = 1
        }
        //数据
        if(account == ''||password == ''|| communityPhone=='' || communityName == '' || province == '请选择' || city == '请选择' || area == '请选择' || check_class == ''|| rebate2 == ''){
            alert('请将信息填写完整！')
        }else{
            var data = {
                "user_name": account,
                "user_pwd": password
            }
            var data2 = {
                "community": communityName,
                "sheng": province,
                "shi": city, 
                "qu": area,
                "shi_lv": rebate,
                "qu_lv": rebate2,
                "type": type,
                "fid": fid
            }
            
            data = JSON.stringify(data);
            data2 = JSON.stringify(data2);
            // console.log(data2)
            postAjax(`${global.apiUrl}/admin_add_community`,function(res){
                // console.log(res)
                if(res == 1){
                    alert('新的社区，添加成功');
                    $('#CommunityModal').modal('hide');
                    getCommunityList(communityPageNo,showNum,communityTxt,sheng,shi,qu); 
                }else if(res == 2){
                    alert('用户名已存在！');
                }
                else if(res == 3){
                    alert('添加社区失败！请重试');
                }
                else if(res == 0){
                    alert('添加社区失败！请重试');
                }
                else if(res == 4){
                    alert('该手机号不存在！请重试');
                }
            },{
                user_content: data,
                pro: data2,
                phone: communityPhone
            })
        }
    })

    //升级市代
    $('#upgradeModal').on('show.bs.modal',function(event){
        var modal = $(this);
        var btnThis = $(event.relatedTarget);
        var upgradeId = btnThis.data('id')
        modal.find('#upgradeId').val(upgradeId);
        $("#province3").val("-1");
        $("#city3").val("-1");
    })

    //搜索门店
    $('#searchBtn2').on('click',function(){
        var province = $('#province3').find('option:selected').text()
        var city = $('#city3').find('option:selected').text()
        if(province == '请选择' || city == '请选择'){
            alert('请选择所在城市')
            return;
        }
        getAjax(`${global.apiUrl}/admin_get_community`,function(res){
            console.log(res);
            var html = '';
            if(res.length == 0){
                html += `
                        <div>暂无社区门店</div>
                    `
            }else{
                for(var i in res){
                
                    html += `
                            <div class="checkbox">
                                <label>
                                    <input type="checkbox" class="class-checked2" value="${res[i].id}"> ${res[i].community}
                                </label>
                            </div>
                        `
                }
                
                
            }
            $('#add-community-box').html(html)
        },{
            sheng: province,
            shi: city,
            type: 2
        })
    })

    //升级市代
    $('#addUpgradeModal').on('click',function(){
        //获取选择的类别
        var obj = document.getElementsByClassName("class-checked2");
        var check_class = [];
        for(k in obj){
            if(obj[k].checked)
                check_class.push(obj[k].value);
        }
        var id = $('#upgradeId').val()
        postAjax(`${global.apiUrl}/admin_up_community`,function(res){
            console.log(res)
        },{
            shi_id: id,
            qu_id: check_class
        })
        
    })

    //查看订单
    $('#communityList').on('click','.orders',function(){
        var communityId = $(this).data('id');
        var sheng = $(this).data('sheng');
        var shi = $(this).data('shi');        
        window.location.href="./orderList.html?"+"communityId="+communityId+"&sheng="+sheng+"&shi="+shi;
    })
});
